from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    """评论表单"""
    # 添加最小长度验证
    content = forms.CharField(
        label='',
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 3,
            'placeholder': '请输入评论内容...',
            'maxlength': 1000
        }),
        min_length=1,
        max_length=1000
    )
    
    class Meta:
        model = Comment
        fields = ['content', 'parent']
        widgets = {
            'parent': forms.HiddenInput()
        }
    
    def clean_content(self):
        """验证评论内容"""
        content = self.cleaned_data.get('content')
        
        # 移除首尾空白字符
        content = content.strip()
        
        # 验证评论长度
        if len(content) < 1:
            raise forms.ValidationError('评论内容不能为空')
        
        if len(content) > 1000:
            raise forms.ValidationError('评论内容不能超过1000个字符')
        
        # 简单的敏感词过滤（示例）
        sensitive_words = ['垃圾', '广告', 'spam']
        for word in sensitive_words:
            if word in content.lower():
                raise forms.ValidationError(f'评论内容包含不合适的词语: {word}')
        
        return content
    
    def clean_parent(self):
        """验证父评论"""
        parent = self.cleaned_data.get('parent')
        # 父评论可以为None，不需要特别验证
        return parent

